<template>
  <div class="ui-add-image">
  
    <Modal
      v-model="showModal"
      title="添加商品"
      :width="modalWidth"
      @on-visible-change="onVisibleChange"
      footer-hide
      :mask-closable="false"
    >
      <div class="select-imgs" v-if="!stepCropper">
        <Tabs :animated="false" v-model="activeTab">
          <TabPane name="images" label="商品库">
            <div class="iai-add-image__picture-center">
              <div class="iai-add-image__picture-sidebar">
                <Menu
                  theme="light"
                  width="140rpx"
                  :active-name="selectSort"
                  v-if="sorts.length"
                  @on-select="sortChange"
                >
                  <MenuGroup title="我的商品">
                    <MenuItem
                      :name="sort.id"
                      v-for="sort in sorts"
                      :key="sort.id"
                    >{{sort.category_name}}</MenuItem>
                  </MenuGroup>
                </Menu>
              </div>
              <div class="iai-add-image__picture-main">
                <div class="iai-add-image__picture-pagination">
                  <Page :current="currentPage" :total="pickerImgsTotal" :page-size="20" simple @on-change="onPageChange"/>
                </div>
                <div class="ice-any-picker">
                  <div
                    class="ice-any-picker__trigger"
                    v-for="(img, i) in pickerImgs"
                    :key="img.key"
                  >
                    <div
                      class="ice-any-picker__trigger-btn"
                      :class="[
                        { 'ice-any-picker__trigger-btn-checked': img.checked }
                      ]"
                      :data-i="i"
                      :data-src="img.url"
                      :data-key="img.key"
                      @click="onPickerTriggerChecked"
                    >
                      <Icon type="md-checkmark" />
                    </div>
                    <div class="iai-add-image__resource-pic">
                      <div class="iai-add-image__resource-pic__cover">
                        <img :src="img.url" draggable="false" />
                      </div>
                      <div class="iai-add-image__resource-pic__title">{{ img.name }}</div>
                    </div>
                  </div>
                      
                </div>
              </div>
            </div>
          </TabPane>
          <TabPane name="upload" label="添加新商品">
            <div class="ui-uploader-sorts">
              <span>请选择素材分类</span>
              <div class="ui-select">
                <Select v-model="goodSort" style="width:200px">
                  <Option
                    v-for="item in sorts"
                    :value="item.id"
                    :key="item.id"
                  >{{ item.category_name }}</Option>
                </Select>
              </div>
            </div>
            <div class="ui-uploader" style="min-height:200px;">
              <Form :label-width="110" style="margin-top:30px;">
                  <FormItem label="链接地址">
                      <Input search enter-button="确定"  v-model="soure_link" placeholder="请输入链接地址"  @on-search="addGoods"/>
                  </FormItem>
              </Form>
              <Spin size="large" fix v-if="loading"></Spin>
            </div>
          </TabPane>
        </Tabs>
        <div class="iai-add-image__selectbar" v-if="pickerSelectesImgs.length">
          <div class="iai-add-image__list">
            <div
              class="iai-add-image__selectbar-item"
              v-for="(img, i) in pickerSelectesImgs"
              :key="img.key"
              
            >
              <div class="iai-add-image__selectbar-item-cover">
                <img :src="img.url" draggable="false" />
              </div>
              <div
                class="iai-add-image__delete"
                :data-i="i"
                :data-key="img.key"
                @click="onRmSelectItem"
              >
                <Icon type="ios-close" />
              </div>
            </div>
          </div>
        </div>
        <div class="ice-add-image-dialog-new__footer">
          <div class="ice-add-image-dialog-new__footer__limit"></div>
          <div class="ice-add-image-dialog-new__footer__operation">
            <Button type="primary" @click="onSubmit" :disabled="!pickerSelectesImgs.length">确定</Button>
            <Button @click="onHide">取消</Button>
          </div>
        </div>
      </div>
      <div v-if="stepCropper && needCrop">
        <ui-cropper
          :images="pickerSelectesImgs"
          @on-export="onCropperExport"
          @on-visible-change="onVisibleChange"
        />
      </div><Spin size="large" fix v-if="spinShow"></Spin>

    </Modal>
  </div>
</template>

<script>
import Setting from '@/setting'
import { getResourceCategory, getResourceItem, getGoodsInfo, getJDGoodsInfo } from '@/api/content/resource'

import util from '@/libs/util'
import UiCropper from './UiCropper.vue'
import UiUploader from './UiUploader.vue'
export default {
  name: 'ui-add-image',
  components: {
    UiCropper,
    UiUploader
  },
  props: {
    show: Boolean,
    needCrop: Boolean,
    images: {
      type: Array,
      default() {
        return []
      }
    },
    maxLength: {
      type: Number,
      default: 9
    },
    mode: {
      type: String,
      default: 'checkbox'
    },
    goodsType: {
        type: String,
        default: 'tb'
    }
  },
  watch: {
    show(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.showModal = newVal
      }
    }
  },
  data() {
    return {
      goodSort: -1,
      activeTab: 'images',
      modalWidth: '984px',
      currentPage: 1,
      pickerImgs: [],
      pickerImgsTotal: 0,
      pickerSelectesImgs: [],
      stepCropper: false,
      showModal: false,
      selectedKeys: [],
      sorts: [],
      selectSort: '0',
      page: 1,
      limit: 10,
      count: 0,
      uploadSorts: [],
      soure_link: '',
      spinShow: false,
      loading: false,
    }
  },
  computed: {},
  methods: {
    onReset() {
      this.activeTab = 'images'
      this.selectSort = '0'
      this.stepCropper = false
      this.modalWidth = '984px'
      this.pickerImgs = []
      this.pickerSelectesImgs = []
      this.uploadData = {}
    },
    onRmSelectItem(e) {
      const { key } = e.currentTarget.dataset
      this.pickerSelectesImgs = this.pickerSelectesImgs.filter(
        item => item.key !== key
      )
      this.pickerImgs = this.pickerImgs.map(item => {
        return {
          ...item,
          checked: item.key === key ? false : item.checked
        }
      })
    },
    getImages(page) {
      this.spinShow = true
      const data = {
        cid: this.selectSort,
        page: page,
        limit: 10
      }
      if(this.goodsType == 'jd')
          data.public = 3
      getResourceItem(data).then(res => {
        const { count, list } = res.data
        this.pickerImgsTotal = count
        this.pickerImgs = list.map(item => {
          let url = ''
          const { desc_json } = item
          switch (typeof desc_json) {
            case 'object':
              url = desc_json.pic_url
              break;
            case 'string':
              url = desc_json
              break;
            default:
              break;
          }
          return {
            ...item,
            name: item.title,
            url,
            key: `${item.id}`,
            checked: this.pickerSelectesImgs.some(img => Number(item.id) === Number(img.key))
          }
        })
        this.spinShow = false
      })
    },
    pageChange (index) {
      this.page = index
      this.getImages()
    },
    sortChange(id) {
      this.selectSort = id
      this.getImages(1)
    },
    onVisibleChange(res) {
      if (res) {
        this.onReset()
        if(this.goodsType == 'jd')
          var categoryType = 3
        else
          var categoryType = 1
        getResourceCategory({
          category_type: categoryType
        }).then(res => {
          const { data } = res
          this.sorts = data
          this.uploadSorts = data
            .filter(item => Number(item.id) !== 0)
            .map(item => ({
              ...item,
              id: Number(item.id)
            }))
        })
        this.getImages(1)
      } else {
        // do something
        this.onHide()
      }
    },
    onPickerTriggerChecked(e) {
      const { i, key } = e.currentTarget.dataset
      const cur = this.pickerImgs.filter(item => item.key === key)[0]
      const selfChecked = cur.checked
      if (this.mode === 'checkbox') {
        this.$set(this.pickerImgs, i, {
          ...cur,
          checked: !selfChecked
        })
        if (selfChecked) {
          this.pickerSelectesImgs = this.pickerSelectesImgs.filter(
            item => item.key !== key
          )
          this.selectedKeys = this.selectedKeys.filter(item => item !== key)
        } else {
          this.pickerSelectesImgs = [...this.pickerSelectesImgs, cur]
          this.selectedKeys = [...this.selectedKeys, key]
        }
      } else {
        this.pickerSelectesImgs = selfChecked ? [] : [cur]
        this.selectedKeys = selfChecked ? [] : [key]
        this.pickerImgs = this.pickerImgs.map(item => {

          let checked = item.checked
          if (item.key === key) {
            if (selfChecked) {
              checked = false
            } else {
              checked = true
            }
          } else {
            checked = false
          }
          return {
            ...item,
            checked
          }
        })
      }
    },
    onSubmit() {
      if (this.needCrop) {
        this.modalWidth = '472px'
        this.stepCropper = true
      } else {
        this.$emit('on-export', {
          images: this.pickerSelectesImgs
        })
        this.onHide()
      }
    },
    onCropperExport(res) {
      this.$emit('on-export', res)
      this.onHide()
    },
    onHide() {
      this.$emit('on-visible-change', false)
    },
    addGoods () {
        if (this.soure_link) {
            var reg = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;
            if (!reg.test(this.soure_link)) {
                return this.$Message.warning('请输入以http开头的地址！');
            }
            let data = {
                link: this.soure_link,
                cid: this.goodSort
            }
            this.loading = true
            if(this.goodsType == 'jd') {
                getJDGoodsInfo(data).then(res => {
                    this.loading = false
                    if (res.status === 200) {
                        var items = [{
                          desc_json: {
                              raw_title: res.data.raw_title,
                              pic_url: res.data.pic_url,
                              view_price: res.data.view_price,
                              detail_url: res.data.detail_url,
                              goods_id: res.data.goods_id,
                              images: res.data.images,
                          }
                        }];
                        this.$emit('on-export', {
                          images: items
                        })
                        this.onHide()
                    } else {
                        this.$Notice.error( {title: res.msg} )
                    }
                }).catch(res => {
                    this.loading = false
                    this.$Message.error(res.msg);
                })
            }else {
                getGoodsInfo(data).then(res => {
                    this.loading = false
                    if (res.status === 200) {
                        var items = [{
                          desc_json: {
                              raw_title: res.data.raw_title,
                              pic_url: res.data.pic_url,
                              view_price: res.data.view_price,
                              detail_url: res.data.detail_url,
                              goods_id: res.data.goods_id,
                              images: res.data.images,
                          }
                        }];
                        this.$emit('on-export', {
                          images: items
                        })
                        this.onHide()
                    } else {
                        this.$Notice.error( {title: res.msg} )
                    }
                }).catch(res => {
                    this.loading = false
                    this.$Message.error(res.msg);
                })
            }

        } else {
            this.$Message.warning('请输入链接地址！');
        }
    },
    onPageChange(i) {
      this.getImages(i)
    }
  },
  mounted() {}
}
</script>
<style lang="scss">
.iai-add-image__picture-sidebar {
  width: 140px;
  flex: 0 0 140px;
  overflow-y: auto;
  .ivu-menu-item-group-title {
    padding-left: 12px;
  }
}
.ice-add-image-dialog-new__footer__operation {
  display: flex;
  .ivu-btn {
    & + .ivu-btn {
      margin-left: 8px;
    }
  }
}
</style>
<style lang="scss" scoped>
.iai-add-image__picture-center {
  display: flex;
  height: 460px;
  border: 1px solid #e7e7e7;
}
.iai-add-image__picture-sidebar {
  width: 140px;
  flex: 0 0 140px;
  overflow-y: auto;
  .ivu-menu {
    height: 100%;
  }
}
.iai-add-image__picture-main {
  flex: 1;
}
.iai-add-image__picture-pagination {
  display: flex;
  justify-content: flex-end;
  padding: 12px 0;
}
.ice-any-picker {
  height: 410px;
  overflow-y: auto;
  display: flex;
  flex-wrap: wrap;
}
.ice-any-picker__trigger {
  margin-left: 12px;
  padding-bottom: 12px;
  position: relative;
}
.iai-add-image__resource-pic {
  width: 145px;
  height: 190px;
  border: 1px solid #e7e7e7;
}
.iai-add-image__resource-pic__cover {
  height: 143px;
  width: 143px;
  overflow: hidden;
  img {
    max-width: 100%;
    max-height: 100%;
    opacity: 1;
    vertical-align: middle;
  }
}
.iai-add-image__resource-pic__title {
  font-size: 12px;
  color: #999;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  padding: 0 10px;
  line-height: 20px;
  padding-top: 5px;
}
.iai-add-image__resource-pic__pix {
  font-size: 12px;
  color: #999;
  padding: 0 10px;
  line-height: 20px;
}
.ice-any-picker__trigger-btn {
  width: 143px;
  height: 143px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  top: 0;
  left: 0;
  cursor: pointer;
  text-align: center;
  color: #fff;
  .ivu-icon {
    font-size: 28px;
    font-weight: bold;
    visibility: hidden;
  }
}
.ice-any-picker__trigger-btn-checked {
  background-color: rgba(#000, 0.5);
  .ivu-icon {
    visibility: visible;
  }
}

.ice-any-picker__trigger-btn-unavailable {
  width: 143px;
  height: 143px;
  line-height: 143px;
  background-color: rgba(255,255,255,.7);
  cursor: not-allowed;
  span{
    font-size: 18px;
    color: #666;
  }
}
</style>
<style lang="scss" scoped>
.ui-uploader-sorts {
  padding-bottom: 8px;
  display: flex;
  align-items: center;
  .ui-select {
    margin-left: 10px;
  }
}
.ui-uploader--inner {
  border: 1px dashed #d8d8d8;
  color: #6af;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
}
</style>